package com.wanglibao.woodtrade.woodtrade.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.ui.activity.CommodityActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.FilterActivity;
import com.wanglibao.woodtrade.woodtrade.ui.activity.SupplyAndDemendActivity;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomeFragmentRecommendAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.Commodity;
import com.wanglibao.woodtrade.woodtrade.util.PullUtil;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshListView;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshBase;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 供需信息
 * Created by lugg on 2016/5/10.
 */
public class ShoppingFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2 {

    @Bind(R.id.tv_commonTitle_title)
    TextView tvTitle;

    @Bind(R.id.tv_commonTitle_right)
    TextView tv_commonTitle_right;

    @Bind(R.id.imgbtn_commonTitle_back)
    ImageButton imgBtnBack;

    @Bind(R.id.rl_common_title)
    RelativeLayout rlCommonTitle;

    @Bind(R.id.tv_fragment_shopping_sales_sort)
    TextView tvfragmentShoppingSalesSort;
    @Bind(R.id.tv_fragment_shopping_price_sort)
    TextView tvfragmentShoppingPriceSort;
    @Bind(R.id.list_fragment_shopping_shoplist)
    PullToRefreshListView listfragmentShoppingShoplist;

    @Bind(R.id.ll_fragment_shopping_null)
    LinearLayout ll_fragment_shopping_null;


    HomeFragmentRecommendAdapter homeFragmentRecommendAdapter;

    int pageIndex = 1;

    Drawable drawable_asc_o, drawable_desc_o, drawable_asc_d, drawable_desc_d;

    String asc = "asc";
    String desc = "desc";

    String price = "price";
    String sales = "sales";
    String goods_click = "goods_click";

    String priceLastSort = desc;
    String salesLastSort = desc;
    String goodsClickLastSort = desc;

    String currentType = "";
    String currentSort = desc;

    boolean all = true;

    String woodTypeId = "";

    @Override
    public void onResume() {
        super.onResume();
        if ((commodity == null || commodity.getList() == null || commodity.getList().size() ==0) && !listfragmentShoppingShoplist.isRefreshing()){
            loadData();
        }
    }

    String woodTypeDetailId = "";

    Commodity commodity;

    String keyword = "";

    String placeId = "";

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 == 2) {
                if (pageIndex == 1){
                    if (commodity != null && commodity.getList() != null){
                        commodity.getList().clear();
                    }
                    homeFragmentRecommendAdapter.update(commodity);
                    if (ll_fragment_shopping_null.getVisibility() == View.GONE){
                        ll_fragment_shopping_null.setVisibility(View.VISIBLE);
                        listfragmentShoppingShoplist.setVisibility(View.GONE);
                    }
                }else{
                    ToastUtil.createLongToast(getContext(),"没有更多数据了");
                    pageIndex--;
                }
            }else{
                Commodity commodity1 = new Gson().fromJson(msg.obj.toString(), Commodity.class);
                if (pageIndex == 1) {
                    commodity = commodity1;
                } else {
                    commodity.getList().addAll(commodity1.getList());
                }
                homeFragmentRecommendAdapter.update(commodity);
                if (ll_fragment_shopping_null.getVisibility() == View.VISIBLE){
                    ll_fragment_shopping_null.setVisibility(View.GONE);
                    listfragmentShoppingShoplist.setVisibility(View.VISIBLE);
                }
            }
            listfragmentShoppingShoplist.onRefreshComplete();
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_shopping, container, false);
        ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT < 19) {
            rlCommonTitle.setPadding(0, 0, 0, 0);
        }
        initView();
        return view;
    }

    private void initView() {
        imgBtnBack.setVisibility(View.GONE);
        tvTitle.setText("商城");
        tv_commonTitle_right.setText("");
        Drawable drawable = getResources().getDrawable(R.mipmap.ic_navigation_classify);
        drawable.setBounds(0,0,drawable.getMinimumWidth(),drawable.getMinimumHeight());
        tv_commonTitle_right.setCompoundDrawables(drawable,null,null,null);
        tv_commonTitle_right.setVisibility(View.VISIBLE);
        addViewClicklistener(tv_commonTitle_right, tvfragmentShoppingSalesSort, tvfragmentShoppingPriceSort);

        drawable_asc_o = getResources().getDrawable(R.mipmap.ic_navbar_o_rise);
        drawable_asc_o.setBounds(0, 0, drawable_asc_o.getMinimumWidth(), drawable_asc_o.getMinimumHeight());
        drawable_asc_d = getResources().getDrawable(R.mipmap.ic_navbar_d_rise);
        drawable_asc_d.setBounds(0, 0, drawable_asc_d.getMinimumWidth(), drawable_asc_d.getMinimumHeight());

        drawable_desc_o = getResources().getDrawable(R.mipmap.ic_navbar_o);
        drawable_desc_o.setBounds(0, 0, drawable_desc_o.getMinimumWidth(), drawable_desc_o.getMinimumHeight());
        drawable_desc_d = getResources().getDrawable(R.mipmap.ic_navbar_d);
        drawable_desc_d.setBounds(0, 0, drawable_desc_d.getMinimumWidth(), drawable_desc_d.getMinimumHeight());

        //通用 初始化
        commodity = new Commodity();
        commodity.setList(new ArrayList<Commodity.ListBean>());
        homeFragmentRecommendAdapter = new HomeFragmentRecommendAdapter(getContext(), commodity);
        listfragmentShoppingShoplist.getRefreshableView().setAdapter(homeFragmentRecommendAdapter);
        listfragmentShoppingShoplist.getRefreshableView().setOnItemClickListener(this);
        listfragmentShoppingShoplist.setMode(PullToRefreshBase.Mode.BOTH);
        listfragmentShoppingShoplist.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
        listfragmentShoppingShoplist.setOnRefreshListener(this);

        PullUtil.initIndicator(listfragmentShoppingShoplist);
//        loadData();
    }

    public void refresh(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                listfragmentShoppingShoplist.setRefreshing();
            }
        }, 500);
    }

    public void loadData() {
        String sort = "";
        if (TextUtils.isEmpty(currentType)) {
            sort = "";
        } else {
            sort = currentType + "-" + currentSort;
        }
        //
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER + NetConfig.TYPE_GOODS,
                NetConfig.lists, handler, "jsonObject", NetConfig.TaskId.lists,
                new Object[]{pageIndex, keyword,
                        woodTypeDetailId,
                        woodTypeId,
                        placeId,
                        sort});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 10) {
            String type = data.getStringExtra("type");
            if (type.equals("filter")) {
                all = false;
                currentType = "";
                currentSort = desc;
                tvfragmentShoppingPriceSort.setText("价格排序");
                tvfragmentShoppingPriceSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                tvfragmentShoppingSalesSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                priceLastSort = desc;
                goodsClickLastSort = desc;
                salesLastSort = desc;

                woodTypeId = data.getStringExtra("woodTypeId");
                woodTypeDetailId = data.getStringExtra("woodTypeDetailId");
                placeId = data.getStringExtra("place_id");
                String woodTypeDetailName = data.getStringExtra("woodTypeDetailName");
                String placeName = data.getStringExtra("place_name");
                tvTitle.setText(woodTypeDetailName+"-"+placeName);
                keyword = "";
                loadData();
            } else if (type.equals("search")) {
                all = true;
                tvfragmentShoppingPriceSort.setText("热度排序");
                currentType = "";
                currentSort = desc;
                tvfragmentShoppingPriceSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                tvfragmentShoppingSalesSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                priceLastSort = desc;
                goodsClickLastSort = desc;
                salesLastSort = desc;

                keyword = data.getStringExtra("keyword");
                woodTypeId = "";
                woodTypeDetailId = "";
                placeId = "";
                tvTitle.setText("商城");
                loadData();
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_commonTitle_right:
                startActivityForResult(new Intent(getActivity(), FilterActivity.class), 100);
                break;
            case R.id.tv_fragment_shopping_sales_sort:
                tvfragmentShoppingSalesSort.setTextColor(getResources().getColor(R.color.orange));
                tvfragmentShoppingPriceSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                if (TextUtils.isEmpty(currentType)) {
                    currentSort = desc;
                    tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                } else if (sales.equals(currentType)) {
                    if (asc.equals(currentSort)) {
                        currentSort = desc;
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                    } else {
                        currentSort = asc;
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_asc_o, null);
                    }
                } else if (goods_click.equals(currentType) || price.equals(currentType)) {
                    if (desc.equals(salesLastSort)) {
                        currentSort = desc;
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                    } else {
                        currentSort = asc;
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_asc_o, null);
                    }
                    String rightSort = "";
                    if (all){
                        rightSort = goodsClickLastSort;
                    }else{
                        rightSort = priceLastSort;
                    }
                    if (desc.equals(rightSort)) {
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                    } else {
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_asc_d, null);
                    }
                }
                salesLastSort = currentSort;
                currentType = sales;
                pageIndex = 1;
                loadData();
                break;
            case R.id.tv_fragment_shopping_price_sort:
                tvfragmentShoppingPriceSort.setTextColor(getResources().getColor(R.color.orange));
                tvfragmentShoppingSalesSort.setTextColor(getResources().getColor(R.color.pressed_color_cccccc));
                if (TextUtils.isEmpty(currentType)) {
                    currentSort = desc;
                    tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                } else if (goods_click.equals(currentType) || price.equals(currentType)) {
                    if (asc.equals(currentSort)) {
                        currentSort = desc;
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                    } else {
                        currentSort = asc;
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_asc_o, null);
                    }
                } else if (sales.equals(currentType)) {
                    String rightSort = "";
                    if (all){
                        rightSort = goodsClickLastSort;
                    }else{
                        rightSort = priceLastSort;
                    }
                    if (desc.equals(rightSort)) {
                        currentSort = desc;
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_desc_o, null);
                    } else {
                        currentSort = asc;
                        tvfragmentShoppingPriceSort.setCompoundDrawables(null, null, drawable_asc_o, null);
                    }
                    if (desc.equals(salesLastSort)) {
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_desc_d, null);
                    } else {
                        tvfragmentShoppingSalesSort.setCompoundDrawables(null, null, drawable_asc_d, null);
                    }
                }

                if (all){
                    currentType = goods_click;
                    goodsClickLastSort = currentSort;
                }else{
                    currentType = price;
                    priceLastSort = currentSort;
                }
                pageIndex = 1;
                loadData();
                break;
        }
    }

    @OnClick(R.id.tv_layout_null_sentInfo) void sentInfoClick(){
        Intent intent = new Intent(getActivity(), SupplyAndDemendActivity.class);
        startActivity(intent);
    }

    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (this.getView() != null)
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(getActivity(), CommodityActivity.class);
        intent.putExtra("id",commodity.getList().get(position-1).getGoods_id());
        startActivity(intent);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pageIndex = 1;
        loadData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        pageIndex++;
        loadData();
    }
}
